import { ProSelectTableModal } from '@/components/ProSelectionTable';
import { createFilterColumns, createTableRequestParams } from '@/utils/table';
import useRouter from '@/utils/useRouter';
import type { ProColumns } from '@ant-design/pro-components';
import {
  EditableProTable,
  PageContainer,
  ProForm,
  ProFormTextArea,
} from '@ant-design/pro-components';
import type { ModalProps as AntdModalProps } from 'antd';
import { Button, Flex, Form, Space } from 'antd';
import { useMemo, useState } from 'react';
import api from './request';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  type: 'warehouse' | 'shipment';
}
export interface ModalProps extends AntdModalProps {
  selectedRows: InventoryManagementApi.ListResponse[];
  onConfirm: (selectedRows: InventoryManagementApi.ListResponse[]) => void;
}
export function ShopSelectionTableModal(props: ModalProps) {
  const [filterList, setFilterList] = useState<Requestor.FilterResponse[]>([]);

  // request
  const getFilterList = async () => {
    // const filterList = await api.getFilterList();
    const filterList: Requestor.FilterResponse[] = [];
    setFilterList(filterList);
    return filterList;
  };
  const getListRequest = (
    params: Requestor.TableParams,
    filterList: Requestor.FilterResponse[],
  ) => {
    const requestParams = createTableRequestParams(params, filterList);
    return api.getList({ ...requestParams });
  };
  const getList = async (params: Requestor.TableParams) => {
    if (!filterList || !filterList.length) {
      const filterList = await getFilterList();
      return getListRequest(params, filterList);
    } else {
      return getListRequest(params, filterList);
    }
  };

  const columns = useMemo(() => {
    const filterColumns = createFilterColumns<InventoryManagementApi.ListResponse>(filterList);
    const tableColumns: ProColumns<InventoryManagementApi.ListResponse>[] = [
      {
        title: '商品名称',
        dataIndex: 'goodsname',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '规格名称',
        dataIndex: 'skuname',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
      {
        title: '金额',
        dataIndex: 'amount',
        hideInSearch: true,
        ellipsis: true,
        align: 'center',
      },
      {
        title: '成本价格',
        dataIndex: 'costPrice',
        hideInSearch: true,
        ellipsis: true,
        align: 'center',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        ellipsis: true,
        hideInSearch: true,
        align: 'center',
      },
    ];
    return filterColumns.concat(tableColumns);
  }, [filterList]);
  return (
    <ProSelectTableModal
      {...props}
      title="选择商品"
      width={1080}
      bodyStyle={{ height: 640, padding: '15px 0' }}
      selectionTableProps={{
        options: false,
        rowKey: 'id',
        toolBarRender: () => [],
        columns,
        request: getList,
        pagination: { defaultPageSize: 10, showSizeChanger: true },
      }}
      onConfirm={(selectedRows) => {
        props.onConfirm(selectedRows);
      }}
    />
  );
}

function ShopListBindForm() {
  const router = useRouter();
  const isWarehouse = router.pathname.includes('warehouse');
  const data = router.query;
  const [form] = Form.useForm();
  const [formData, setFormData] = useState<any>({ remark: '' });
  const [isShow, setIsShow] = useState(false);
  const [shopList, setShopList] = useState<any[]>([]);

  const findData = (id: string, list: any[]) => {
    for (let [index, item] of list.entries()) {
      if (item.id === id) return index;
    }
    return -1;
  };
  const back = () => {
    router.replace('/goods/inventory-management');
  };
  const onSubmit = async () => {
    const params: any = {
      remarks: formData.remark,
      model: shopList.map((item) => {
        return {
          inventoryId: data.id,
          skuName: item.skuname,
          warehouseQTY: item.inventoryQty,
        };
      }),
    };
    const request = isWarehouse ? api.updateWarehouse : api.updateShipment;
    const res = await request(params);
    if (res.success) {
      back();
    }
    return data.success;
  };

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(() => [].map((item) => item));
  const columns: ProColumns<InventoryManagementApi.ListResponse>[] = [
    {
      title: '规格名称',
      dataIndex: 'skuname',
      readonly: true,
    },
    {
      title: '库存数量',
      dataIndex: 'inventoryQty',
      valueType: 'digit',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            const index = findData(record.id, shopList);
            if (index > -1) {
              const list = JSON.parse(JSON.stringify(shopList));
              list.splice(index, 1);
              setShopList(list);
            }
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer
      extra={[
        <Button
          key="add"
          type="primary"
          onClick={() => {
            setIsShow(true);
          }}
        >
          选择商品
        </Button>,
      ]}
    >
      <div style={{ height: 420 }}>
        <EditableProTable<InventoryManagementApi.ListResponse>
          controlled
          rowKey="id"
          toolBarRender={false}
          recordCreatorProps={false}
          columns={columns}
          editable={{
            type: 'multiple',
            editableKeys,
            onChange: setEditableRowKeys,
            actionRender: (_, __, dom) => {
              return [dom.save, dom.delete];
            },
          }}
          value={shopList}
          onChange={(shopList) => {
            setShopList([...shopList]);
          }}
        />
      </div>

      <ProForm
        form={form}
        onValuesChange={(_: any, values: any) => {
          setFormData(values);
        }}
        submitter={{
          submitButtonProps: { style: { display: 'none' } },
          resetButtonProps: { style: { display: 'none' } },
        }}
      >
        <ProForm.Item>
          <ProFormTextArea
            name="remark"
            label="备注"
            placeholder="请输入备注"
            fieldProps={{
              value: formData?.remark,
              onChange: (e) =>
                setFormData({
                  ...formData,
                  remark: e.target.value,
                }),
            }}
          />
        </ProForm.Item>
      </ProForm>
      <Flex justify="flex-end">
        <Space>
          <Button onClick={back}>取消</Button>
          <Button type="primary" onClick={onSubmit}>
            保存
          </Button>
        </Space>
      </Flex>

      <ShopSelectionTableModal
        open={isShow}
        selectedRows={shopList}
        onConfirm={(selectedRows) => {
          setShopList(selectedRows);
          setIsShow(false);
        }}
        onCancel={() => {
          setIsShow(false);
        }}
      />
    </PageContainer>
  );
}

export default ShopListBindForm;
